//
//  EmotionKeyboardViewController.swift
//  表情键盘
//
//  Created by mac on 15/5/23.
//  Copyright (c) 2015年 mac. All rights reserved.
//

import UIKit
///Step: 6 
private var emoticonscell = "emoticonscell"
class EmotionKeyboardViewController: UIViewController {
    var completeEmosion:((emotion:Emotions) -> ())? ///Step: <21> 定义闭包变量
    //--------------step <21>---重写控制器的构造方法 实现点击次控制器上的按钮能吧按钮上对应的模型对象传递给父控制器-----
    init(completeEmosion:(emotion:Emotions) -> ())   ///Step:<21> 定义一个闭包参数用来传递模型对象
    {
        super.init(nibName: nil, bundle: nil)
        self.completeEmosion = completeEmosion ///Step: <21>
    }
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    //--------------step 16---建立表情数组----------------------------------------------------------
    lazy var emotionList: [Emotions] =
    {
      return Emotions.emostionsList()
    }()
    
    //--------------step 4---自定义键盘的总体布局----------------------------------------------------------
    lazy var toolbar:UIToolbar = {
        
        var index = 0
        let tool = UIToolbar(frame: CGRectZero)
        var items = [AnyObject]()
        let itemNames = ["最近","默认","emoji","浪小花"]
        for str in itemNames
        {
            let m = UIBarButtonItem(title: str, style: UIBarButtonItemStyle.Plain, target: self, action: "selectItem:")
            m.tag = index
            items.append(m)
            
        ///Step: 4 弹簧
        if index++ < 3{
           items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
           }
        
        }
        tool.items = items
        return tool
        
    }()
    
    //--------------step 5---添加表情容器瀑布VC----------------------------------------------------------
    lazy var collectionview:UICollectionView={
        let layout = UICollectionViewFlowLayout() ///Step: 7 实现每一页显示21个
        let w = UIScreen.mainScreen().bounds.width / 7
        layout.itemSize = CGSizeMake(w, w)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection=UICollectionViewScrollDirection.Horizontal
        layout.sectionInset = UIEdgeInsetsMake(4, 0, 0, 0)
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        cv.backgroundColor = UIColor.whiteColor()
        cv.pagingEnabled=true
        cv.dataSource = self
        cv.delegate = self ///Step: 20 实现点击表情符号键盘外面的控制器能拿到模型对象
        cv.registerClass(EmotionCell.self, forCellWithReuseIdentifier: emoticonscell)
        return cv
        
    }()
    ///Step: 4
    func selectItem(item: UIBarButtonItem)
    {
        println(item.tag)
        var index = 0
        switch item.tag
        {
        case 0:
            index = 0
        case 1:
            index = 1
        case 2:
            index = 7
        case 3:
            index = 11
        default:
            index = 0
            
        }
        
        let indexpath = NSIndexPath(forItem: index*21, inSection: 0)
        collectionview.scrollToItemAtIndexPath(indexpath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    
    }
    //--------------step 5-------将添加控件的行为让loadView执行-----------------------------------------------------
    override func loadView() {
        super.loadView()
        setupUI()
    }
    func setupUI()
    {
        view.backgroundColor = UIColor.redColor()
        view.addSubview(toolbar)
        view.addSubview(collectionview)
        toolbar.setTranslatesAutoresizingMaskIntoConstraints(false)
        collectionview.setTranslatesAutoresizingMaskIntoConstraints(false)
        var cons = [AnyObject]()
        //--------------step 6---设置自动布局----------------------------------------------------------
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionview]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["collectionview":collectionview])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolbar]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["toolbar":toolbar])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionview]-[toolbar(44)]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["collectionview":collectionview,"toolbar":toolbar])
        view.addConstraints(cons)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
}

//--------------step 6---显示cell----------------------------------------------------------
extension EmotionKeyboardViewController: UICollectionViewDataSource,UICollectionViewDelegate
{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return emotionList.count  ///Step: 16
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionview.dequeueReusableCellWithReuseIdentifier(emoticonscell, forIndexPath: indexPath) as! EmotionCell
//        cell.backgroundColor = indexPath.item % 2==0 ? UIColor.redColor() : UIColor.grayColor()
        cell.backgroundColor = UIColor.whiteColor()
        cell.emosion = emotionList[indexPath.item]
        return cell
    }
    
    //--------------step 20---实现点击表情按钮能触发事件----------------------------------------------------------
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
         if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? EmotionCell
         {
            self.completeEmosion!(emotion: cell.emosion!)
            
         }
        
    }
    
    
}
//--------------step 7---自定义cll----------------------------------------------------------
class EmotionCell: UICollectionViewCell
{
     var emotionBtn = UIButton()
     override init(frame: CGRect) {
     super.init(frame: frame)
     emotionBtn.frame = CGRectInset(bounds, 0, 0)
     emotionBtn.backgroundColor = UIColor.whiteColor()
     emotionBtn.userInteractionEnabled = false ///Step: 20
     emotionBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
     addSubview(emotionBtn)
        
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    //--------------step 17---cell的模型属性----------------------------------------------------------
    var emosion: Emotions?{
        didSet{
            if emosion?.imagePath != nil{
                emotionBtn.setImage(UIImage(contentsOfFile: emosion!.imagePath!), forState: UIControlState.Normal)
            }
            else
            {
                emotionBtn.setImage(nil, forState: UIControlState.Normal)
            }
            ///Step: 19 设置国际通用表情
            emotionBtn.setTitle(emosion?.emojiStr ?? "", forState: UIControlState.Normal)
            ///Step: 20 给删除按钮设置图片
            if emosion!.isEmptyButton {
                
                emotionBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal )
                emotionBtn.setImage(UIImage(named: "compose_emotion_delete_Highlighted"), forState: UIControlState.Highlighted)
            }
            
        }
        
    }
    
}


